require 'uri'
require 'rss'

class Category < ActiveRecord::Base
  belongs_to :category
  has_many :medias

  validates_presence_of :label
  validates_length_of :label,:maximum => 64
  validates_length_of :url, :maximum => 128
  validates_length_of :img_url, :maximum => 128
  validates_associated :category


  @bordel_cat = find(:first, :conditions =>"label = 'Bordel'")
  @master_cat_1 = find(:first, :conditions =>"label = 'Films'")
  @master_cat_2 = find(:first, :conditions =>"label = 'Jeux ISO'")
  @master_cat_3 = find(:first, :conditions =>"label = 'TV Anime'")

  def self.get_bordel_cat_id
    return @bordel_cat.id if @bordel_cat
  end

  def self.master_cat_1
    return @master_cat_1
  end
  def self.master_cat_2
    return @master_cat_2
  end
  def self.master_cat_3
    return @master_cat_3
  end

  def self.rss_feeded_categories
    return find(:all, :conditions => ["url != \"\""])
  end


  def update_rss()
    if rss_xml = download_rss()
    rss = nil
    begin
      rss = RSS::Parser.parse(rss_xml,true)
    rescue RSS::InvalidRSSError
      rss = RSS::Parser.parse(rss_xml,false)
    end
    if rss
        items = rss.channel.items
        items.each do |item|
          guid = item.guid.content.to_i
          if guid > 0
            unless media = Media.find_by_id(guid)
              media = Media.new
              media.id = guid
              media.user_id = 0
            end
            media.nom = item.title.strip.capitalize
            desc = item.description.to_s.split('<br>')
            media.fichier =  desc[3].gsub(/Nom du fichier : /, '').strip
            if item.link
              item.link = item.link.gsub(/^http:\/\/anonym.to\/\?/, '')
              media.url = item.link.strip
            end
            media.category_id = self.id
            media.nfo = desc[0].gsub(/Catégorie : /, '').strip
            media.langue = desc[1].gsub(/Langue : /, '').strip
            media.details = desc[2].gsub(/Newsgroup : /, '').strip
            media.taille = desc[4].gsub(/Taille : /,'').strip
            if media.save
              puts "Media was saved!"  if defined?DEBUG
            else
              media.errors.each_full { |msg| puts msg }  if defined?DEBUG
            end
          end
        end
       return true
      end
    end
    return false
  end

    private
  def download_rss()
    if rss_url = url
    bn_url = URI.parse('http://www.binnews.in')
    if defined?HTTP_PROXY
      socket = Net::HTTP::Proxy(HTTP_PROXY,HTTP_PROXY_PORT);
    else
      socket = Net::HTTP
    end
    res = socket.start(bn_url.host, bn_url.port) {|http|
      http.get(rss_url)
    }
    return (res ? res.body : res)
    else
      return nil
    end
  end

end
